package com.party.course.controller;

import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hbga.xunpay.Xunpay;
import com.hbga.xunpay.XunpayClient;
import com.hbga.xunpay.exception.XunpayException;
import com.hbga.xunpay.model.ChannelTransparentReqModel;
import com.hbga.xunpay.request.ChannelTransparentRequest;
import com.hbga.xunpay.response.ChannelTransparentResponse;
import com.party.common.core.domain.AjaxResult;
import com.party.common.utils.StringUtils;
import com.party.course.domain.CorporateMerchantInfo;
import com.party.course.domain.RealNameInfo;
import com.party.course.domain.StudentInfo;
import com.party.course.service.IRealNameInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 特约商户入网(企业/个体)控制器
 */
@RestController
@RequestMapping("/corporateMerchant")
public class CorporateMerchantController {


    @Autowired
    private IRealNameInfoService realNameInfoService;



    @Value("${huidiao.domain}")
    private String domainurl;


    @PostMapping("/addRegiserSignMe")
    public AjaxResult addRegiserSignMe(@RequestBody RealNameInfo realNameInfo) {
        String id = realNameInfo.getId();
        RealNameInfo realNameInfoquery = realNameInfoService.getById(id);
        if (realNameInfoquery != null) {
            // 校验下面参数为必填
            if (StringUtils.isEmpty(realNameInfoquery.getSignName())) {
                return AjaxResult.error("请填写商户名称");
            }
            if (StringUtils.isEmpty(realNameInfoquery.getShortName())) {
                return AjaxResult.error("请填写商户简称");
            }
            if (StringUtils.isEmpty(realNameInfoquery.getLicenceNo())) {
                return AjaxResult.error("请填写营业执照编号");
            }

            if (StringUtils.isEmpty(realNameInfoquery.getNetLicenceUrl())) {
                return AjaxResult.error("请上传营业执照");
            }
            if (StringUtils.isEmpty(realNameInfoquery.getLegalName())) {
                return AjaxResult.error("请填写法人姓名");
            }
            if (StringUtils.isEmpty(realNameInfoquery.getLegalLicenceNo())) {
                return AjaxResult.error("请填写法人身份证号码");
            }
            if (StringUtils.isEmpty(realNameInfoquery.getNetFrontUrl())) {
                return AjaxResult.error("请填写身份证正面地址");
            }
            if (StringUtils.isEmpty(realNameInfoquery.getNetBackUrl())) {
                return AjaxResult.error("请填写身份证反面地址");
            }
            if (StringUtils.isEmpty(realNameInfoquery.getMobile())) {
                return AjaxResult.error("请填写手机号");
            }
            // 经营地址的判断
            if (StringUtils.isEmpty(realNameInfoquery.getProvince()) || StringUtils.isEmpty(realNameInfoquery.getCity()) || StringUtils.isEmpty(realNameInfoquery.getDistrict()) || StringUtils.isEmpty(realNameInfoquery.getAddress())) {
                return AjaxResult.error("请填写经营地址");
            }
            // 开户行和银行卡号
            if (StringUtils.isEmpty(realNameInfoquery.getBankCode()) || StringUtils.isEmpty(realNameInfoquery.getBankCardNo())) {
                return AjaxResult.error("请填写开户行和银行卡号");
            }


        }

        CorporateMerchantInfo corporateMerchantInfo = new CorporateMerchantInfo();
        corporateMerchantInfo.setMchTransparentNo("MCH_" + IdUtil.simpleUUID());
        corporateMerchantInfo.setNotifyUrl(domainurl+"/kcsm/corporateMerchant/notify");
        corporateMerchantInfo.setBusinessRole("SETTLED_MERCHANT");
        corporateMerchantInfo.setParentMerchantNo("10091478670");
        corporateMerchantInfo.setRequestNo("kcheng" + IdUtil.simpleUUID());
        // 商户主题信息
        corporateMerchantInfo.setSignName(realNameInfoquery.getSignName());
        corporateMerchantInfo.setShortName(realNameInfoquery.getShortName());
        corporateMerchantInfo.setSignType("ENTERPRISE"); // 添加签约类型
        corporateMerchantInfo.setLicenceNo(realNameInfoquery.getLicenceNo());
        corporateMerchantInfo.setLicenceUrl(realNameInfoquery.getNetLicenceUrl());
        // 商户法人信息
        corporateMerchantInfo.setLegalName(realNameInfoquery.getLegalName());
        corporateMerchantInfo.setLegalLicenceType("ID_CARD");
        corporateMerchantInfo.setLegalLicenceNo(realNameInfoquery.getLegalLicenceNo());
        //身份证反面地址
        corporateMerchantInfo.setLegalLicenceFrontUrl(realNameInfoquery.getNetFrontUrl());
        //身份证反面地址
        corporateMerchantInfo.setLegalLicenceBackUrl(realNameInfoquery.getNetBackUrl());
        corporateMerchantInfo.setMobile(realNameInfoquery.getMobile());
        // 经营地址
        corporateMerchantInfo.setProvince(realNameInfoquery.getProvince());
        corporateMerchantInfo.setCity(realNameInfoquery.getCity());
        corporateMerchantInfo.setDistrict(realNameInfoquery.getDistrict());
        corporateMerchantInfo.setAddress(realNameInfoquery.getAddress());
        // 开通产品信息 json
        JSONObject productInfo = new JSONObject();
        productInfo.put("productCode", "D1");
        productInfo.put("rateType", "SINGLE_FIXED");
        productInfo.put("fixedRate", "0");
        // 添加结算产品
        JSONObject settlementProduct = new JSONObject();
        settlementProduct.put("productCode", "ENTERPRISE_WITHDRAW_STANDARD_REALTIME"); // 结算产品代码，需要根据实际接口文档确认
        settlementProduct.put("rateType", "SINGLE_FIXED");
        settlementProduct.put("fixedRate", "1");
        JSONArray productList = new JSONArray();
        productList.add(productInfo);
        productList.add(settlementProduct);
        corporateMerchantInfo.setProductInfo(productList.toJSONString());
        // 商户联系人信息
        corporateMerchantInfo.setContactName(realNameInfoquery.getContactName());
        corporateMerchantInfo.setContactMobile(realNameInfoquery.getContactMobile());
        corporateMerchantInfo.setContactEmail(realNameInfoquery.getContactEmail());

        // 结算账户信息
        corporateMerchantInfo.setSettlementDirection("ACCOUNT");
        corporateMerchantInfo.setBankCode(realNameInfoquery.getBankCode());
        corporateMerchantInfo.setBankAccountType("ENTERPRISE_ACCOUNT"); // 企业账户
        corporateMerchantInfo.setBankCardNo(realNameInfoquery.getBankCardNo());
        JSONObject res = this.registerCorporateMerchant(corporateMerchantInfo);
        String returnCode = res.getString("returnCode");
        String requestNo = res.getString("requestNo");
        String applicationNo = res.getString("applicationNo");
        String applicationStatus = res.getString("applicationStatus");
        String transparentId = res.getString("transparentId");
        String merchantNo = res.getString("merchantNo");
        String returnMsg = res.getString("returnMsg");

        realNameInfoquery.setRequestNo(requestNo);
        realNameInfoquery.setApplicationNo(applicationNo);
        realNameInfoquery.setApplicationStatus(applicationStatus);
        realNameInfoquery.setMerchantNo(merchantNo);
        realNameInfoquery.setTransparentId(transparentId);
        realNameInfoquery.setRemark("returnCode:"+returnCode+";"+"returnMsg:"+returnMsg);
        realNameInfoService.updateById(realNameInfoquery);
        return AjaxResult.success(returnMsg);

    }

    /**
     * 特约商户入网(企业/个体)
     *
     * @param merchantInfo 商户信息
     * @return 入网结果
     */
    public JSONObject registerCorporateMerchant(CorporateMerchantInfo merchantInfo) {
        try {
            // 配置支付参数（根据实际环境配置）
            Xunpay.mchNo = "M1752112514"; // 商户号
            Xunpay.appId = "686f1d82e4b02e1c8b4b5935"; // 应用ID
            //秘钥
            Xunpay.apiKey = "fPqfOo0sVJ31uvWZPH3iRvnNIkJDeW0bajMWaU7lJPvXNlA2RgI4E3TA68qstVd1YXeMYqH8zTra460UItPDcVZ8Kk6iPR1AgvpBQCSqIOa9rCsGeQ1vHi35jWXRPeTe";
            XunpayClient xunpayClient = new XunpayClient();
            ChannelTransparentRequest request = new ChannelTransparentRequest();
            ChannelTransparentReqModel model = new ChannelTransparentReqModel();
            // 设置基础参数
            model.setMchNo(Xunpay.mchNo);
            model.setAppId(Xunpay.appId);
            model.setCtCode("yeepay_JJ002"); // 固定值
            model.setMchTransparentNo(merchantInfo.getMchTransparentNo());
            model.setNotifyUrl(merchantInfo.getNotifyUrl());
            // 构建params参数
            Map<String, String> params = new HashMap<>();

            params.put("businessRole", merchantInfo.getBusinessRole());
            params.put("parentMerchantNo", merchantInfo.getParentMerchantNo());

            // 商户主体信息
            JSONObject merchantSubjectInfo = new JSONObject();
            merchantSubjectInfo.put("signName", merchantInfo.getSignName());
            merchantSubjectInfo.put("shortName", merchantInfo.getShortName());
            merchantSubjectInfo.put("signType", merchantInfo.getSignType());
            merchantSubjectInfo.put("licenceNo", merchantInfo.getLicenceNo());
            merchantSubjectInfo.put("licenceUrl", merchantInfo.getLicenceUrl());
            params.put("merchantSubjectInfo", merchantSubjectInfo.toJSONString());

            // 商户法人信息
            JSONObject merchantCorporationInfo = new JSONObject();
            merchantCorporationInfo.put("legalName", merchantInfo.getLegalName());
            merchantCorporationInfo.put("legalLicenceType", merchantInfo.getLegalLicenceType());
            merchantCorporationInfo.put("legalLicenceNo", merchantInfo.getLegalLicenceNo());
            merchantCorporationInfo.put("legalLicenceFrontUrl", merchantInfo.getLegalLicenceFrontUrl());
            merchantCorporationInfo.put("legalLicenceBackUrl", merchantInfo.getLegalLicenceBackUrl());
            merchantCorporationInfo.put("mobile", merchantInfo.getMobile());
            params.put("merchantCorporationInfo", merchantCorporationInfo.toJSONString());

            // 商户联系人信息
            JSONObject merchantContactInfo = new JSONObject();
            merchantContactInfo.put("contactName", merchantInfo.getContactName());
            merchantContactInfo.put("contactMobile", merchantInfo.getContactMobile());
            merchantContactInfo.put("contactEmail", merchantInfo.getContactEmail());
            merchantContactInfo.put("contactLicenceNo", merchantInfo.getContactLicenceNo());
            merchantContactInfo.put("adminEmail", merchantInfo.getAdminEmail());
            merchantContactInfo.put("adminMobile", merchantInfo.getAdminMobile());
            params.put("merchantContactInfo", merchantContactInfo.toJSONString());

            // 经营类目
            JSONObject industryCategoryInfo = new JSONObject();
            industryCategoryInfo.put("primaryIndustryCategory", merchantInfo.getPrimaryIndustryCategory());
            industryCategoryInfo.put("secondaryIndustryCategory", merchantInfo.getSecondaryIndustryCategory());
            params.put("industryCategoryInfo", industryCategoryInfo.toJSONString());

            // 经营地址
            JSONObject businessAddressInfo = new JSONObject();
            businessAddressInfo.put("province", merchantInfo.getProvince());
            businessAddressInfo.put("city", merchantInfo.getCity());
            businessAddressInfo.put("district", merchantInfo.getDistrict());
            businessAddressInfo.put("address", merchantInfo.getAddress());
            params.put("businessAddressInfo", businessAddressInfo.toJSONString());

            params.put("productInfo", merchantInfo.getProductInfo());


            // 结算账户信息
            JSONObject settlementAccountInfo = new JSONObject();
            settlementAccountInfo.put("settlementDirection", merchantInfo.getSettlementDirection());
            settlementAccountInfo.put("bankCode", merchantInfo.getBankCode());
            settlementAccountInfo.put("bankAccountType", merchantInfo.getBankAccountType());
            settlementAccountInfo.put("bankAccountName", merchantInfo.getBankAccountName());
            settlementAccountInfo.put("bankCardNo", merchantInfo.getBankCardNo());
            params.put("settlementAccountInfo", settlementAccountInfo.toJSONString());


            // 将params转为JSON字符串
            model.setParams(JSON.toJSONString(params));
            request.setBizModel(model);

            // 发起请求
            ChannelTransparentResponse response = (ChannelTransparentResponse) xunpayClient.execute(request);
            System.out.println("kkkkkkkkkkk999999999");
            // 处理响应结果
            if (response.isSuccess(Xunpay.apiKey)) {
                // 解析res字段获取详细信息
                JSONObject data = JSON.parseObject(JSON.toJSONString(response.getData()));
                String resStr = data.getString("res");
                JSONObject res = JSON.parseObject(resStr);

                JSONObject result = new JSONObject();
                result.put("returnCode", res.getString("returnCode"));
                result.put("returnMsg", res.getString("returnMsg"));
                result.put("requestNo", res.getString("requestNo"));
                result.put("applicationNo", res.getString("applicationNo"));
                result.put("applicationStatus", res.getString("applicationStatus"));
                result.put("merchantNo", res.getString("merchantNo"));
                result.put("transparentId", res.getString("transparentId"));
                return result;
            } else {
                JSONObject errorResult = new JSONObject();
                errorResult.put("returnCode", "FAIL");
                errorResult.put("returnMsg", "请求失败");
                return errorResult;
            }
        } catch (XunpayException e) {
            JSONObject errorResult = new JSONObject();
            errorResult.put("returnCode", "ERROR");
            errorResult.put("returnMsg", "系统异常: " + e.getMessage());
            return errorResult;
        } catch (Exception e) {
            JSONObject errorResult = new JSONObject();
            errorResult.put("returnCode", "ERROR");
            errorResult.put("returnMsg", "系统异常: " + e.getMessage());
            return errorResult;
        }
    }


    public static void main(String[] args) {
        CorporateMerchantController corporateMerchantController = new CorporateMerchantController();
        CorporateMerchantInfo corporateMerchantInfo = new CorporateMerchantInfo();
        corporateMerchantInfo.setMchTransparentNo("MCH_" + IdUtil.simpleUUID());
        corporateMerchantInfo.setNotifyUrl("http://zp.cc/kcsm/corporateMerchant/notify");
        corporateMerchantInfo.setBusinessRole("SETTLED_MERCHANT");
        corporateMerchantInfo.setParentMerchantNo("10091478670");
        corporateMerchantInfo.setRequestNo("kcheng" + IdUtil.simpleUUID());
        // 商户主题信息
        corporateMerchantInfo.setSignName("智维云图（重庆）科技有限公司");
        corporateMerchantInfo.setShortName("智维云图");
        corporateMerchantInfo.setSignType("ENTERPRISE"); // 添加签约类型
        corporateMerchantInfo.setLicenceNo("91500000MAE7W7X882");
        corporateMerchantInfo.setLicenceUrl("http://staticres.yeepay.com/jcptb-merchant-netinjt05/2025/07/31/merchant-1753926873913-b1717c80-a381-4f0a-819c-dc1dd67a8d10-lfomuDVutmnSkJHnHryE.jpg");
        // 商户法人信息
        corporateMerchantInfo.setLegalName("董环俊");
        corporateMerchantInfo.setLegalLicenceType("ID_CARD");
        corporateMerchantInfo.setLegalLicenceNo("622323199303210822");
        corporateMerchantInfo.setLegalLicenceFrontUrl("http://staticres.yeepay.com/jcptb-merchant-netinjt05/2025/07/31/merchant-1753925985924-b4d87bf1-19d8-47d8-821e-f2975b6a5084-FnEkuHaBDzRrbNiSLRKe.jpg");
        corporateMerchantInfo.setLegalLicenceBackUrl("http://staticres.yeepay.com/jcptb-merchant-netinjt05/2025/07/31/merchant-1753925988177-c3050f46-94f6-4600-9b0c-e002f22fcbac-zMACEcmSecUJKXTREVgW.jpg");
        corporateMerchantInfo.setMobile("17753166467");
        // 经营地址
        corporateMerchantInfo.setProvince("500000");
        corporateMerchantInfo.setCity("500100");
        corporateMerchantInfo.setDistrict("500105");
        corporateMerchantInfo.setAddress("重庆市两江新区大竹林街道黄山大道中段1号数字经济发展展示中心附A25-01-1003");
        // 开通产品信息 json
        JSONObject productInfo = new JSONObject();
        productInfo.put("productCode", "D1");
        productInfo.put("rateType", "SINGLE_FIXED");
        productInfo.put("fixedRate", "0");
        // 添加结算产品
        JSONObject settlementProduct = new JSONObject();
        settlementProduct.put("productCode", "ENTERPRISE_WITHDRAW_STANDARD_REALTIME"); // 结算产品代码，需要根据实际接口文档确认
        settlementProduct.put("rateType", "SINGLE_FIXED");
        settlementProduct.put("fixedRate", "1");
        JSONArray productList = new JSONArray();
        productList.add(productInfo);
        productList.add(settlementProduct);
        corporateMerchantInfo.setProductInfo(productList.toJSONString());
        // 商户联系人信息
        corporateMerchantInfo.setContactName("董环俊");
        corporateMerchantInfo.setContactMobile("17753166467");
        corporateMerchantInfo.setContactEmail("zhangsan@example.com");
//        corporateMerchantInfo.setContactLicenceNo("622323199303210822");


        // 结算账户信息
        corporateMerchantInfo.setSettlementDirection("ACCOUNT");
        corporateMerchantInfo.setBankCode("ECITIC");
        corporateMerchantInfo.setBankAccountType("ENTERPRISE_ACCOUNT"); // 企业账户
        // corporateMerchantInfo.setBankAccountName("张三测试商户");
        corporateMerchantInfo.setBankCardNo("8111201012900726720");

        Object o = corporateMerchantController.registerCorporateMerchant(corporateMerchantInfo);
        System.out.println(o);

//        String kk="\"{\\\"applicationStatus\\\":\\\"AGREEMENT_SIGNING\\\",\\\"applicationNo\\\":\\\"TYSHRW20250803113048294802\\\",\\\"agreementSignUrl\\\":\\\"https://mp.yeepay.com/0/gnscoU2ksFy\\\",\\\"requestNo\\\":\\\"S1951848195764187138\\\",\\\"merchantNo\\\":\\\"10091600693\\\"}\"";
//        String unescaped = kk.substring(1, kk.length() - 1).replace("\\\"", "\"");
//        JSONObject object = JSONObject.parseObject(unescaped);
//        System.out.println(object);


    }

    /**
     * 商户入网结果通知回调接口
     *
     * @param notifyData 通知数据
     * @return 处理结果
     */
    @PostMapping("/notify")
    public Object merchantNotify(@RequestBody JSONObject notifyData) {
        try {


            String transparentId = notifyData.getString("transparentId");
            String res = notifyData.getString("res");
            String appId = notifyData.getString("appId");
            String sign = notifyData.getString("sign");
            // 解码res

            // 解码res
            String decodedRes = URLDecoder.decode(res, StandardCharsets.UTF_8);
            System.out.println("Decoded Res: " + decodedRes);
//            String unescaped = decodedRes.substring(1, decodedRes.length() - 1).replace("\\\"", "\"");
            JSONObject jsonObject = JSONObject.parseObject(decodedRes);
            // 直接解析 decodedRes，它已经是一个合法的JSON字符串
            System.out.println("Parsed JSON Object: " + jsonObject.toJSONString());

            // 处理通知数据
            // 记录日志或更新数据库状态
            System.out.println("收到商户入网通知:");
            System.out.println("transparentId: " + transparentId);
            System.out.println("res: " + res);
            System.out.println("sign: " + sign);
            System.out.println("appId: " + appId);
            String requestNo = jsonObject.getString("requestNo");
            if(StringUtils.isNotEmpty(requestNo)){
                QueryWrapper<RealNameInfo>  realNameInfoQueryWrapper = new QueryWrapper<>();
                realNameInfoQueryWrapper.eq("request_no",requestNo);
                List<RealNameInfo> list = realNameInfoService.list(realNameInfoQueryWrapper);
                if(list.size()>0){
                    RealNameInfo realNameInfo = list.get(0);
                    // 如果不是已完成状态
                    // 如果不是已完成状态
                    if(!"COMPLETED".equals(realNameInfo.getApplicationStatus())){
                        realNameInfo.setApplicationStatus(jsonObject.getString("applicationStatus"));
                        realNameInfo.setAgreementSignUrl(jsonObject.getString("agreementSignUrl"));
                        realNameInfo.setRequestNo(jsonObject.getString("requestNo"));
                        realNameInfo.setMerchantNo(jsonObject.getString("merchantNo"));
                        realNameInfo.setRemark(jsonObject.toJSONString());
                        realNameInfo.setTransparentId(transparentId);
                        realNameInfoService.updateById(realNameInfo);
                    }
                }

            }


            // 输出解析结果
            System.out.println("applicationStatus: " + jsonObject.getString("applicationStatus"));
            System.out.println("applicationNo: " + jsonObject.getString("applicationNo"));
            System.out.println("agreementSignUrl: " + jsonObject.getString("agreementSignUrl"));
            System.out.println("requestNo: " + jsonObject.getString("requestNo"));
            System.out.println("merchantNo: " + jsonObject.getString("merchantNo"));


            // 返回成功响应
            JSONObject result = new JSONObject();
            result.put("code", "SUCCESS");
            result.put("message", "处理成功");
            return result;
        } catch (Exception e) {
            JSONObject result = new JSONObject();
            String message = e.getMessage();
            result.put("code", "FAIL");
            result.put("message", "处理失败: " + e.getMessage());
            return result;
        }
    }
}
